<?php
	session_start();
    require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'../model/Context/BaseContext.php';
    require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'../model/Service/AuthenticationService.php';
    require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'../model/Service/MemberService.php';
     require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'../model/Service/UserService.php';
    require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'../model/Service/ScheduleService.php';
    require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'../model/ServiceResult/ServiceResult.php';
    require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'../_config/setting/global.setting.php';
    require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'../_config/setting/SMTPConfig.php';
    require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'../plugin/Config/Config.php';
	if(isset($_GET['type']) && isset($_GET['action']))
	{
		$context = new BaseContext();
		$result = new ServiceResult();
		$type = $_GET['type'];
		$action = $_GET['action'];
		switch ($type) {
			case "login":
				$authenticationService = new AuthenticationService();	
				switch ($action) {
					case "login":
						if(isset($_POST['username']) && isset($_POST['password']))
						{
							$username = $_POST['username'];
							$password = $_POST['password'];
							//----------------------
							//Check if the user has already tried to login
							//If they have, set the variable $auth_tries to the value of the cookie and get the expire time
							if (isset($_COOKIE['time_limit'])) {
								$num_tries = $_COOKIE['auth_attempts'];
								$expire_time = $_COOKIE['time_limit'];
							} else {
								 //If they haven't, create the cookie with a value of 1, since this is their first attempt
								setcookie('auth_attempts', 1, time()+900); //Cookie named 'auth_attempts' with a stored value of '1' that expires in 900 seconds from now (15 minutes)
								setcookie('time_limit', time()+900, time()+900); //Cookie named 'time_limit' that stores the expiration time of the first login attempt
								$num_tries = 1; //Value of 1
								$expire_time = time()+900; //Timestamp of 15 minutes from now
							}
							//Check if the user has exceeded 3 login attempts in 15 minutes
							//If true, log the current timestamp in the DB and let the user know they are temporarily locked out
							if ($num_tries > 3) {
								$lockout_time = time() + 3600; //Timestamp of 1 hour from now
								//UPDATE lockouttime to database
								$authenticationService->updateLockOutTimeByName($context, $result, $username, $lockout_time);
								$num_tries = 1;
								setcookie('auth_attempts', 1, time()+900);
								echo "<script>alert('You have failed to log in 3 times in 15 minutes!  You must wait an hour before attempting to log in again.');window.location='index.php?func=login';</script>";
							}
							$lockOutTime = $authenticationService->getLockOutTimeByUserName($context, $result, $username);
							if($lockOutTime!= null && $lockOutTime> time())
								echo "<script>alert('User Locked ! You must wait an hour to attempt to log in again!');window.location='index.php?func=login';</script>";
							else {
								$loginResult = $authenticationService->login($context, $result, $username, $password);
								if($loginResult != false)
								{
									$_SESSION['user']['ID'] = $loginResult->getUserID();
									$_SESSION['user']['username'] = $loginResult->getUserName();
									$_SESSION['user']['lastLogin'] = $loginResult->getLastLogin();
									$dateTime = date('Y-m-d h:i:s', time());
									$loginResult->setLastLogin($dateTime);
									$authenticationService->update($context, $result, $loginResult);
									setcookie('auth_tries', '', time()-3600);
									setcookie('time_limit', '', time()-3600);
									if(isset($_SESSION['gotoPage']))
									{
										echo "<script>window.location='".$_SESSION["gotoPage"]."';</script>";
									}
									else 
									{
										echo "<script>window.location='index.php?func=dash';</script>";
									}
								
									header("Location:index.php?func=dash");
								}
								else 
								{
									$num_tries++; //Increment $auth_tries to reflect the failed login attempt
									setcookie('auth_attempts', $num_tries, $expire_time); //Update your 'auth_attempts' cookie
									echo "<script>alert('Login Failed!!!');window.location='index.php?func=login';</script>";
								}
							}
						}					
					break;				
					case "logout":
						session_destroy();
						header("Location:index.php?func=login");
						die();			
					break;
					case "changePass":
					 	if(isset($_SESSION['user']))
					    {
					    	$userService = new UserService();
					        $id = $_SESSION['user']['ID'];
							$oldpass = Tool::md5_base64($_POST['oldPass']);
							$newpass = $_POST['newPass'];
							$confirmPass = $_POST['confirmNewPass'];
							$user = $userService->findByOid($context, $result, $id);
							if($newpass == $confirmPass && $user->getPass() == $oldpass)
							{
								$userService->changePass($context, $result, $newpass,$id);
								session_destroy();
								echo "<script>alert('Change Password Success!!!');window.location='index.php?func=login';</script>";
								die();	
							}	
							else echo "<script>alert('Change Password Fail!!!');window.location='index.php?func=dash';</script>";	
					    }
					    else 
					    	header("Location:index.php?func=login");		
					break;
					default:
						echo "khong co tinh nang nay";
					break;
				}							
			break;
			case "schedule":
				$memberService = new MemberService();
				$scheduleService = new ScheduleService();
				switch ($action) {
					
					case "add":
							$data = array();
							foreach ($_POST as $key => $value) {
								$data[$key] = $value;
							}
							echo "<pre style='background:white' >";
							print_r($data);
							echo "</pre>";
							
							$data['deliveryTime']= Tool::convert12hTo24h($data['deliveryTime']);
							$data['collectionTime']= Tool::convert12hTo24h($data['collectionTime']);
							
							$memberDomain = null;
							$scheduleDomain = new ScheduleDomain($data);
							if(isset($_POST['chooseClient']) && $_POST['chooseClient'] == 0)
							{
								$memberDomain = $memberService->findByOid($context, $result, $_POST['client']);
								$scheduleDomain->setDwoNumber($memberDomain->getDwo());
								$scheduleDomain->setStatus(0);
								$scheduleService->createSchedule($context, $result, $scheduleDomain);		
							}
							else 
							{
								$memberDomain = new MemberDomain($data);
								$scheduleDomain->setDwoNumber($memberDomain->getDwo());
								$scheduleDomain->setStatus(0);
								$schedule = new Schedule($scheduleDomain);																
								$schedule->setMemberDomain($memberDomain);
								$memberid = $memberService->createMember($context, $result, $schedule);
							}
							header("Location:index.php?func=schedule&opt=listNewSchedule");
					break;
					
					case "acceptSchedule":
						
							if(isset($_GET['scheduleID']))
							{
								$schedule = $scheduleService->getScheduleByOid($context, $result, $_GET['scheduleID']);
								$schedule->getScheduleDomain()->setStatus(1);
								$scheduleService->updateSchedule($context, $result, $schedule->getScheduleDomain());
							}
						
							header("Location:index.php?func=schedule&opt=listAlertDelivery");
						
					break;
					
					case "updateSchedule":
						
							if(isset($_GET['scheduleID']))
							{
								$data = array();
								foreach ($_POST as $key => $value) {
									$data[$key] = $value;
								}
								$scheduleDomain = new ScheduleDomain($data);
								$scheduleService->updateSchedule($context, $result, $scheduleDomain);
							}
							
							header("Location:index.php?func=schedule&opt=viewDeliverySchedule&scheduleID=".$_GET['scheduleID']);
						
					break;
					
					case "completeSchedule":
						
							if(isset($_GET['scheduleID']))
							{
								$data = array();
								foreach ($_POST as $key => $value) {
									$data[$key] = $value;
								}
								$schedule = $scheduleService->getScheduleByOid($context, $result, $_GET['scheduleID']);
								$schedule->getScheduleDomain()->setCollectionDateLive($data['collectionDateLive']);
								$schedule->getScheduleDomain()->setCollectionTimeLive($data['collectionTimeLive']);
								$schedule->getScheduleDomain()->setTransportDriverLive($data['transportDriverLive']);
								$schedule->getScheduleDomain()->setJobDescriptionLive($data['jobDescriptionLive']);
								$schedule->getScheduleDomain()->setStatus(2);
								
								$scheduleService->updateSchedule($context, $result, $schedule->getScheduleDomain());
							}
							
							header("Location:index.php?func=schedule&opt=listAlertCollection");
						
					break;
					
					case "deleteSchedule":
							if(isset($_GET['scheduleID']))
							{
								$scheduleService->deleteSchedule($context, $result, $_GET['scheduleID']);
							}					
							header("Location:index.php?func=schedule&opt=listNewSchedule");
					break;
					
					case "edit":
						
					break;
					
					default:
						echo "khong co tinh nang nay";
					break;
				}							
			break;
			//start process config 
			
				
			
			case "website":
				switch ($action) {
					case "hostConfig":
						if(isset($_POST['btn_submit']))
						{
							$c1 = new Config(); 
							$root1 =& $c1->parseConfig(dirname(__FILE__).DIRECTORY_SEPARATOR.'../_config/setting/setting.ini', 'inifile'); 
		        			$settingsSection =& $root1->getItem("section", "delivery-collection-schedule");
							$host =& $settingsSection->getItem("directive", "delivery_collection_schedule_MYSQL_HOST");
							$dbName =& $settingsSection->getItem("directive", "delivery_collection_schedule_MYSQL_NAME");
							$user =& $settingsSection->getItem("directive", "delivery_collection_schedule_MYSQL_USER");
							$pass =& $settingsSection->getItem("directive", "delivery_collection_schedule_MYSQL_PASS");
		        			
		        			$host->setContent(Tool::encode($_POST['host'], "sTunnInVietnAm@2012#"));
		        			$dbName->setContent(Tool::encode($_POST['dbName'], "sTunnInVietnAm@2012#"));
		        			$user->setContent(Tool::encode($_POST['user'], "sTunnInVietnAm@2012#"));
		        			$pass->setContent(Tool::encode($_POST['pass'], "sTunnInVietnAm@2012#"));
		        			
		        			$c1->writeConfig();
							header("Location:index.php?func=website&opt=hostConfig");	
						}				
					break;
					case "globalConfig":
						if(isset($_POST['btn_submit']))
						{
							$glb["websiteURL"] = $_POST['websiteURL'];
							$glb["settingDir"] = $_POST['settingDir'];
							$glb["layoutDir"] = $_POST['layoutDir'];
							$glb["controllerDir"] = $_POST['controllerDir'];
							$glb["contactEmail"] = $_POST['contactEmail'];

							// write configuration back 
							// read configuration data and get reference to root 
							$c0 = new Config(); 
							$root0 =& $c0->parseConfig($glb, "PHPArray"); 
							
							$options0 = array('name' => 'glb'); 
							// write configuration to file as PHP array 
							$c0->writeConfig(dirname(__FILE__).DIRECTORY_SEPARATOR."../_config/setting/global.setting.php", "PHPArray", $options0);
							header("Location:index.php?func=website&opt=globalConfig");	
						}				
					break;
					case "emailConfig":
						if(isset($_POST['btn_submit']))
						{
							$smtp["host"] = Tool::encode($_POST['hostEmail'], "sTunnInVietnAm@2012#");
							$smtp["port"] = Tool::encode($_POST['port'], "sTunnInVietnAm@2012#");
							$smtp["user"] = Tool::encode($_POST['userHost'], "sTunnInVietnAm@2012#");
							$smtp["pass"] = Tool::encode($_POST['passHost'], "sTunnInVietnAm@2012#");

							// write configuration back 
							// read configuration data and get reference to root 
							$c2 = new Config(); 
							$root2 =& $c2->parseConfig($smtp, "PHPArray"); 
							
							$options2 = array('name' => 'smtp'); 
							// write configuration to file as PHP array 
							$c2->writeConfig(dirname(__FILE__).DIRECTORY_SEPARATOR."../_config/setting/SMTPConfig.php", "PHPArray", $options2);
							header("Location:index.php?func=website&opt=emailConfig");	
						}				
					break;
					
					default:
						echo "khong co tinh nang nay";
					break;
				}							
			break;	
			//end config
			
			case "web":
				$authenticationService = new AuthenticationService();	
				$host = Tool::decode($smtp['host'], "sTunnInVietnAm@2012#");
			    $port = Tool::decode($smtp['port'], "sTunnInVietnAm@2012#");
			    $user = Tool::decode($smtp['user'], "sTunnInVietnAm@2012#");
			    $pass = Tool::decode($smtp['pass'], "sTunnInVietnAm@2012#"); 
				$emailService = new EmailService($host, $port, $user, $pass);
				
				$accountService = new AccountService();
				
				switch ($action) {
					case "editEmail":
						if($permit == true)
						{
							$data = array();
							foreach ($_POST as $key => $value) {
								$data[$key] = addslashes($value);
							}
							$emailDomain = new EmailDomain($data);
							
							$emailService->updateEmailByObj($context, $result, $emailDomain);
							header("Location:index.php?func=web&opt=email");	
						}
						else 
							header("Location:index.php?func=dash");						
					break;	
					
					case "addEmail":
						if($permit == true)
						{
							$data = array();
							foreach ($_POST as $key => $value) {
								$data[$key] = addslashes($value);
							}
							$emailDomain = new EmailDomain($data);
							$emailService->createEmail($context, $result, $emailDomain);
							header("Location:index.php?func=web&opt=email");	
						}
						else 
							header("Location:index.php?func=dash");					
					break;	
					
					case "deleteEmail":
						if($permit == true)
						{
							$mailID = $_GET['id'];
							$emailService->deleteEmailByOid($context, $result, $mailID);
							header("Location:index.php?func=web&opt=email");	
						}
						else 
							header("Location:index.php?func=dash");			
					break;	
					
					default:
						echo "khong co tinh nang nay";
					break;
				}							
			break;
			
			default:
				echo "khong co tinh nang nay";
			break;
		}
	}
	else
	{
		echo "ERROR";
	}